package com.print;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.Region;

import javax.imageio.ImageIO;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.attribute.HashAttributeSet;
import javax.print.attribute.standard.PrinterName;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by xxd on 2017/12/13.
 */
public class PrintYNK2 {
    private String modelTyp;//打印模板
    private Integer loop;
    private Boolean imgFlg;//是否打印表头图片
    private String cusId;

    public String getModelTyp() {
        return modelTyp;
    }
    public void setModelTyp(String modelTyp) {
        this.modelTyp = modelTyp;
    }
    public Integer getLoop() {
        return loop;
    }
    public void setLoop(Integer loop) {
        this.loop = loop;
    }
    public Boolean getImgFlg() {
        return imgFlg;
    }
    public void setImgFlg(Boolean imgFlg) {
        this.imgFlg = imgFlg;
    }
    public String getCusId() {
        return cusId;
    }
    public void setCusId(String cusId) {
        this.cusId = cusId;
    }

    public PrintYNK2(String modelTyp, Integer loop, Boolean imgFlg, String cusId){
        this.modelTyp = modelTyp;
        this.loop = loop;
        this.imgFlg = imgFlg;
        this.cusId = cusId;
    }
    /**
     * 新建Workbook
     * @throws IOException
     */
    public HSSFWorkbook creatWorkbook() throws IOException{

        InputStream in = null;
        if(modelTyp.equals("1")){//for 来料检
            in = LabelAppletComm.class.getResourceAsStream("/com/excel/ynk/001.xls");
        }else if(modelTyp.equals("2")) {//for
            in = LabelAppletComm.class.getResourceAsStream("/com/excel/ynk/DM002.xls");
        }

        HSSFWorkbook workbook = new HSSFWorkbook(in);

        for (int i = 0; i < loop; i++) {
            HSSFSheet newsheet = null;
            HSSFSheet fromsheet = workbook.getSheetAt(0);
            newsheet = workbook.createSheet("sheet" + (String.valueOf(i + 1)));
            copyRows(workbook, fromsheet, newsheet, fromsheet.getFirstRowNum(), fromsheet.getLastRowNum());
            //设置工作簿缩放比例  ,"缩放"设置中，将所有列调整为一列
            newsheet.setAutobreaks(true);
            workbook.setPrintArea(
                    0, //工作薄 下标0开始
                    0, //起始列 下标0开始
                    8, //终止列 下标0开始
                    0, //起始行 下标0开始
                    26  //终止行 下标0开始
            );
            //设定边距
            newsheet.setMargin(HSSFSheet.TopMargin,fromsheet.getMargin(HSSFSheet.TopMargin));// 页边距（上）
            newsheet.setMargin(HSSFSheet.BottomMargin,fromsheet.getMargin(HSSFSheet.BottomMargin));// 页边距（下）
            newsheet.setMargin(HSSFSheet.LeftMargin,fromsheet.getMargin(HSSFSheet.LeftMargin) );// 页边距（左）
            newsheet.setMargin(HSSFSheet.RightMargin,fromsheet.getMargin(HSSFSheet.RightMargin));// 页边距（右 ）
            newsheet.setHorizontallyCenter(true); //设置打印页面为水平居中
            newsheet.setVerticallyCenter(true); //设置打印页面为垂直居中
            HSSFPrintSetup printSetup = newsheet.getPrintSetup();
            //A4纸
            printSetup.setPaperSize(HSSFPrintSetup.A4_PAPERSIZE);
            //设定纵向
            printSetup.setLandscape(false); // 打印方向，true：横向，false：纵向(默认)
            printSetup.setFitHeight((short) 1);//设置缩放调整为页高
            printSetup.setFitWidth((short) 1);//设置缩放调整为页宽
        }

        workbook.removeSheetAt(0);
        in.close();

        return workbook;
    }
    /**
     * 复制模板
     *
     * @param workbook
     * @param fromsheet
     * @param newsheet
     * @param firstrow
     * @param lastrow
     *
     * copySheet("template", "test2", "d:/template.xls");
     * @throws IOException
     */
    @SuppressWarnings("deprecation")
    public void copyRows(HSSFWorkbook workbook, HSSFSheet fromsheet,
                         HSSFSheet newsheet, int firstrow, int lastrow) throws IOException {
        ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
        if(imgFlg) {
            InputStream in = LabelApplet4JX.class.getResourceAsStream("/com/excel/YNK.jpg");
            BufferedImage bufferImg = ImageIO.read(in);
            ImageIO.write(bufferImg, "jpg", byteArrayOut);
            HSSFPatriarch patriarch = newsheet.createDrawingPatriarch();
            //anchor主要用于设置图片的属性
            //dx1 : 起始单元格的x偏移量 dx2：终止单元格的x偏移量
            //dy1：起始单元格的y偏移量 dy2：终止单元格的y偏移量
            //col1：起始单元格列序号，从0开始计算；col2：终止单元格列序号，从0开始计算；
            HSSFClientAnchor anchor = new HSSFClientAnchor(0, 50, 180, 200, (short) 0, 0, (short) 1, 0);
            anchor.setAnchorType(3);
            //插入图片
            patriarch.createPicture(anchor, workbook.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
            if ((firstrow == -1) || (lastrow == -1) || lastrow < firstrow) {
                return;
            }
        }
        // 拷贝合并的单元格
        Region region = null;
        for (int i = 0; i < fromsheet.getNumMergedRegions(); i++) {
            region = fromsheet.getMergedRegionAt(i);
            if ((region.getRowFrom() >= firstrow)
                    && (region.getRowTo() <= lastrow)) {
                newsheet.addMergedRegion(region);
            }
        }
        HSSFRow fromRow = null;
        HSSFRow newRow = null;
        HSSFCell newCell = null;
        HSSFCell fromCell = null;
        // 设置列宽
        for (int i = firstrow; i <= lastrow; i++) {
            fromRow = fromsheet.getRow(i);
            if (fromRow != null) {
                for (int j = fromRow.getLastCellNum(); j >= fromRow.getFirstCellNum(); j--) {
                    int colnum = fromsheet.getColumnWidth(j);
                    if (colnum > 100) {
                        newsheet.setColumnWidth(j,colnum);
                    }
                    if (colnum == 0) {
                        newsheet.setColumnHidden(j,true);
                    } else {
                        newsheet.setColumnHidden(j,false);
                    }
                }
                break;
            }
        }
        // 拷贝行并填充数据
        for (int i = 0; i <= lastrow; i++) {
            fromRow = fromsheet.getRow(i);
            if (fromRow == null) {
                continue;
            }
            newRow = newsheet.createRow(i - firstrow);
            newRow.setHeight(fromRow.getHeight());
            for (int j = fromRow.getFirstCellNum(); j < fromRow.getPhysicalNumberOfCells(); j++) {
                fromCell = fromRow.getCell((short) j);
                if (fromCell == null) {
                    continue;
                }
                newCell = newRow.createCell((short) j);
                newCell.setCellStyle(fromCell.getCellStyle());
                int cType = fromCell.getCellType();
                newCell.setCellType(cType);
                switch (cType) {
                    case HSSFCell.CELL_TYPE_STRING:
                        newCell.setCellValue(fromCell.getRichStringCellValue());
                        break;
                    case HSSFCell.CELL_TYPE_NUMERIC:
                        newCell.setCellValue(fromCell.getNumericCellValue());
                        break;
                    case HSSFCell.CELL_TYPE_FORMULA:
                        newCell.setCellFormula(fromCell.getCellFormula());
                        break;
                    case HSSFCell.CELL_TYPE_BOOLEAN:
                        newCell.setCellValue(fromCell.getBooleanCellValue());
                        break;
                    case HSSFCell.CELL_TYPE_ERROR:
                        newCell.setCellValue(fromCell.getErrorCellValue());
                        break;
                    default:
                        newCell.setCellValue(fromCell.getRichStringCellValue());
                        break;
                }
            }
        }
    }

    /**
     * 打印Excel
     * @param filePath
     */
    public void printExcel(String printerName,String filePath){
        ComThread.InitSTA(true);
        Dispatch excel = null;
        ActiveXComponent xl = new ActiveXComponent("Excel.Application");
        HashAttributeSet has = new HashAttributeSet();
        has.add(new PrinterName(printerName, null));
        PrintService[] services = PrintServiceLookup.lookupPrintServices(null, has);

        try {
            // 这里Visible是控制文档打开后是可见还是不可见，若是静默打印，那么第三个参数就设为false就好了
            Dispatch.put(xl, "Visible", new Variant(false));
            Dispatch workbooks = xl.getProperty("Workbooks").toDispatch();
            // 打开文档
            excel = Dispatch.call(workbooks, "Open", filePath)
                    .toDispatch();

            Dispatch sheets = Dispatch.get((Dispatch) excel, "Sheets")
                    .toDispatch();

            // 获得几个sheet,并打印
            int count = Dispatch.get(sheets, "Count").getInt();
            System.out.println(count);
            for (int j = 1; j <=count; j++) {
                Dispatch sheet = Dispatch.invoke(sheets, "Item",
                        Dispatch.Get, new Object[] { new Integer(j) },
                        new int[1]).toDispatch();
                Dispatch pageSetup = Dispatch.get(sheet, "PageSetup").toDispatch();
                if(modelTyp.equals("2") ||
                        modelTyp.equals("7") ||
                        modelTyp.equals("8") ||
                        modelTyp.equals("9")){
                    Dispatch.put(pageSetup, "Orientation", new Variant(1));//纵向打印
                }else{
                    Dispatch.put(pageSetup, "Orientation", new Variant(2));//横向打印
                }

                if(services == null || services.length == 0){
                    Dispatch.call(sheet, "PrintOut");
                }else{
                    Dispatch.callN(sheet,"PrintOut",new Object[]{Variant.VT_MISSING, Variant.VT_MISSING, 1,//打印一份
                            new Boolean(false),printerName, new Boolean(true),Variant.VT_MISSING, ""});
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //增加以下三行代码解决文件无法删除bug
//	        Dispatch.call(excel, "save");
            Dispatch.call(excel,  "Close" ,  new  Variant(false));
            excel=null;
            //关闭文档
            xl.invoke("Quit",new Variant[] {});
            xl = null;
            // 始终释放资源
            ComThread.Release();
        }
    }

    public String creatYNKFile(String lot_id){
        String filepath = "C:\\YNK";
        File file = new File(filepath);
        if(!file.exists()){
            file.mkdirs();
        }
        return (filepath + "\\"+"DM-" + lot_id + ".xls");
    }
    }

